<?php

/**
 * This file is part of Switcher.
 * 
 * Switcher is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Switcher is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Switcher. If not, see <http://www.gnu.org/licenses/>.
 * 
 * @license http://www.opensource.org/licenses/gpl-3.0.html GPL-3.0
 */

namespace switcher\utils;

/**
 * Utility class for Json-related operations.
 * 
 * @author Dri <switcher.framework@gmail.com>
 * @license http://www.opensource.org/licenses/gpl-3.0.html GPL-3.0
 * @package switcher\utils
 * @since 1.0.0
 */
final class JsonHelper
{
	/**
	 * Hidden constructor
	 */
	private function __construct()
	{
	}
	
	/**
	 * Decode a <i>JSON</i> array from a string.
	 * 
	 * @param string $json The json array being decoded
	 * @param bool $array When true, returned objects will be converted into associative arrays
	 */
	public static function decodeJsonArray($json, $array = false)
	{
		$value = json_decode('{"wrapper":' . $json . '}', $array);
		
		if ($value !== null)
		{
			$value = $array ? $value['wrapper'] : $value->wrapper;
		}
		
		return $value;
	}
	
	/**
	 * Load a <i>JSON</i> object from a file.
	 * 
	 * @param string $file The file to load
	 * @param bool $array When true, returned objects will be converted into associative arrays
	 * @return mixed An object, an array or <i>null</i> if the file doesn't exist
	 * @see json_decode()
	 * @see FileHelper::loadFile()
	 */
	public static function loadJson($file, $array = false)
	{
		$json = FileHelper::loadFile($file);
		return $json === false ? null : json_decode($json, $array);
	}
	
	/**
	 * Load a <i>JSON</i> array from a file.
	 * 
	 * @param string $file The file to load
	 * @param bool $array When true, returned objects will be converted into associative arrays.
	 * @return mixed An array or <i>null</i> if the file doesn't exist
	 * @see self::decodeJsonArray()
	 * @see FileHelper::loadFile()
	 */
	public static function loadJsonArray($file, $array = false)
	{
		$json = FileHelper::loadFile($file);
		return $json === false ? null : self::decodeJsonArray($json, $array);
	}
}

?>